package com.tevintao.marketingsystem.task;

import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.tevintao.marketingsystem.log.LogManager;
import com.tevintao.marketingsystem.services.ViewOperation;
import com.tevintao.marketingsystem.xposted.WxTaskManger;


/**
 * 自己人聊天
 */
public class ChatSelfFriendTaskProcess extends SetTaskExtra {
    private static ChatSelfFriendTaskProcess ourInstance = new ChatSelfFriendTaskProcess();

    public static ChatSelfFriendTaskProcess getInstance() {
        return ourInstance;
    }

    private ChatSelfFriendTaskProcess() {
    }

    public static final int LOOK_UP_MAX_ITEM_NUM = 50;

    @SuppressWarnings("ResourceType")
    @Override
    public boolean processView(String contextName, View v) {
        if (WxUiViewConfig.MAIN_LAUNCH.equals(contextName)) {
            //先检查是否在聊天界面
            View chatViewGroupView = v.findViewById(WxUiViewConfig.CHAT_VIEW_GROUP_VIEW);
            LogManager.getInstance().logInfo("chatViewGroupView " + chatViewGroupView + (null == chatViewGroupView ? "null == chatViewGroupView  " : " null == chatViewGroupView visual " + chatViewGroupView.getVisibility()));
            if (null != chatViewGroupView && chatViewGroupView.getVisibility() == View.VISIBLE) {
                //聊天界面已经打开
                LogManager.getInstance().logInfo("聊天界面已经打开");
                return chatViewProcess((ViewGroup) chatViewGroupView);
            }
            boolean inWxTab = WxUiViewConfig.inTab(v, WxUiViewConfig.TAB_WEIXIN);
            LogManager.getInstance().logInfo("inWxTab = " + inWxTab);
            if (inWxTab) {
                Object needChatNickName = getExtra(WxUiViewConfig.KEY_NEED_CHAT_NICK_NAME);
                if (null == needChatNickName) {
                    taskError(v.getContext(), WxTaskManger.TASK_SATE_EXTRA_ERROR, "没有聊天昵称");
                }

                //在微信TAB页面
                View chatListView = v.findViewById(WxUiViewConfig.CHAT_LIST_VIEW);
                if (null != chatListView && chatListView instanceof ListView) {
                    ListView chatLV = (ListView) chatListView;
                    int firstVisual = chatLV.getFirstVisiblePosition();
                    int lastVisual = chatLV.getLastVisiblePosition();
                    int headCount = chatLV.getHeaderViewsCount();

                    int start;
                    if (firstVisual == 0) {
                        start = headCount;
                    } else {
                        start = 0;
                    }
                    View needChatView = null;
                    for (int i = start, len = chatLV.getChildCount(); i < len; i++) {
                        LogManager.getInstance().logInfo("---------------------------------------------------------------");
                        View childView = chatLV.getChildAt(i);
                        View chatItem = childView.findViewById(WxUiViewConfig.CHAT_LIST_ITEM);
                        if (null != chatItem && !TextUtils.isEmpty(chatItem.getContentDescription()) && chatItem.getContentDescription().toString().startsWith(needChatNickName.toString())) {
                            needChatView = chatItem;
                            break;
                        }
                        LogManager.getInstance().logInfo("chatItem = " + chatItem);
//                        JSONObject joTree = HookWindowManagerGlobal.GetViewJsonTree((ViewGroup) childView, -1);
//                        HookWindowManagerGlobal.printViewTreeJson(joTree, 0);
                        LogManager.getInstance().logInfo("---------------------------------------------------------------");
                    }
                    if (null != needChatView) {
                        LogManager.getInstance().logInfo("找到聊天联系人");
//                        WxUiViewConfig.printViewGroup((ViewGroup) v);
                        ViewOperation.clickView(needChatView);
                    } else if (lastVisual < LOOK_UP_MAX_ITEM_NUM) {
                        LogManager.getInstance().logInfo("本页没有找到 移动到下一页 ");
                        if (lastVisual + chatLV.getFooterViewsCount() >= chatLV.getCount()) {
                            LogManager.getInstance().logInfo("已经移动到末尾了");//启用搜索模式
                            WxUiViewConfig.clickSearchButton((ViewGroup) v);
                        } else {
                            ViewOperation.moveListPosition(chatLV, lastVisual);
                        }
                        LogManager.getInstance().logInfo("firstVisual = " + firstVisual + " lastVisual = " + lastVisual + " headCount = " + headCount + " " + chatLV.getAdapter().getCount() + "  " + chatLV.getCount() + " " + chatLV.getFooterViewsCount());
                    } else {
                        WxUiViewConfig.clickSearchButton((ViewGroup) v);
                    }

                }
            }
        } else if (WxUiViewConfig.VIEW_MAIN_LAUNCHER_SEARCH.equals(contextName)) {
            View editText = v.findViewById(WxUiViewConfig.ID_SEARCH_EDIT_TEXT);
            if (editText != null && editText instanceof EditText) {
                Object searchName = getExtra(WxUiViewConfig.KEY_NEED_CHAT_NICK_NAME);
                if (null == searchName || TextUtils.isEmpty(searchName.toString())) {
                    taskError(v.getContext(), WxTaskManger.TASK_SATE_EXTRA_ERROR, "没有搜索的关键字");
                    return true;
                } else {
                    TextView inputView = (TextView) editText;
                    if (searchName.toString().equals(inputView.getText().toString())) {
                        LogManager.getInstance().logInfo("已经输入内容");

                        View searchResult = WxUiViewConfig.getViewByIdAndContent((ViewGroup) v, WxUiViewConfig.ID_SEARCH_NICK_NAME_RESULT_CONTENT, searchName.toString());
                        LogManager.getInstance().logInfo("查找聊天昵称的View = " + searchResult);
                        if (null != searchResult) {
                            ViewOperation.clickView(searchResult);
                        } else {
                            taskError(v.getContext(), WxTaskManger.TASK_SATE_FIND_FRIEND_ERROR, "查找好友失败");
                        }
//                        WxUiViewConfig.printViewGroup((ViewGroup) v);
                    } else {
                        ViewOperation.setText(editText, getExtra(WxUiViewConfig.KEY_NEED_CHAT_NICK_NAME).toString());
                    }
                }
            }
        } else if (WxUiViewConfig.CHAT_UI.equals(contextName)) {
//            WxUiViewConfig.printViewGroup((ViewGroup) v);
            chatViewProcess((ViewGroup) v);
        } else if (WxUiViewConfig.VIEW_SUBSCRIBE_LIST.equals(contextName)) {
            View backButton = v.findViewById(WxUiViewConfig.ID_SUBSCRIBE_LIST_BACK);
            if (null != backButton) {
                ViewOperation.clickView(backButton);
            }
        } else if (WxUiViewConfig.DIALOG_CLASS.equals(contextName)) {
            View info = v.findViewById(WxUiViewConfig.DIALOG_INFO_TEXT);
            if (null != info) {
                TextView tv = (TextView) info;
                String promptMessage = tv.getText().toString();
                if ("用户不存在".equals(promptMessage)) {
                    LogManager.getInstance().logError("搜索的用户不存在");
                    taskError(v.getContext(), WxTaskManger.TASK_SATE_TASK_PAST, "搜索的用户不存在");
                }
            }
        }
        return false;
    }

    @SuppressWarnings("ResourceType")
    private boolean chatViewProcess(ViewGroup chatViewGroup) {
        /**
         * START 此处添加一个处理，在微商版本中，可能需要聊的人不同，做一个判断，是否是当前聊的人
         */
        View title = chatViewGroup.findViewById(WxUiViewConfig.CHAT_VIEW_NICK_NAME_TITLE);
        if (null != title && title instanceof TextView) {
            TextView titleView = (TextView) title;
            String nickName = titleView.getText().toString();
            Object searchName = getExtra(WxUiViewConfig.KEY_NEED_CHAT_NICK_NAME);
            if (null != searchName) {
                if (searchName.toString().equals(nickName)) {
                    LogManager.getInstance().logInfo("聊天的人是同一个");
                } else {
                    LogManager.getInstance().logInfo("聊天不是同一个人");
                    View backButton = chatViewGroup.findViewById(WxUiViewConfig.CHAT_VIEW_BACK_BUTTON);
                    if (null != backButton) {
                        ViewOperation.clickView(backButton);
                    }
                    return false;
                }
            } else {
                LogManager.getInstance().logInfo("聊天人的昵称是" + searchName);
            }
        } else {
            LogManager.getInstance().logInfo("没有找到标题");
        }
        /**
         * END 此处添加一个处理，在微商版本中，可能需要聊的人不同，做一个判断，是否是当前聊的人
         */
//        WxUiViewConfig.printViewGroup(chatViewGroup);
        Object sendMessage = getExtra(WxUiViewConfig.KEY_CHAT_CONTENT);
        if (null == sendMessage || TextUtils.isEmpty(sendMessage.toString())) {
            taskError(chatViewGroup.getContext(), WxTaskManger.TASK_SATE_EXTRA_ERROR, "聊天-发送的消息，获取失败");
            return false;
        }
        View inputView = chatViewGroup.findViewById(WxUiViewConfig.CHAT_VIEW_EDIT_TEXT);
        if (null != inputView && inputView instanceof EditText) {
            EditText editText = (EditText) inputView;
            String currentInputContent = editText.getText().toString();
            if (TextUtils.isEmpty(currentInputContent)) {
                ViewOperation.setText(inputView, sendMessage.toString());
            } else {
                View sendButton = chatViewGroup.findViewById(WxUiViewConfig.CHAT_VIEW_SEND_BUTTON);
                if (null != sendButton) {
                    ViewOperation.clickView(sendButton);
                    taskError(chatViewGroup.getContext(), WxTaskManger.TASK_SATE_SUCCESS, "发送消息成功 ");
                }
            }
        }
        return false;
    }
}
